﻿using NineTeam.DTO;
using Senparc.Weixin.MP;
using Senparc.Weixin.MP.AdvancedAPIs;
using Senparc.Weixin.MP.AdvancedAPIs.OAuth;
using Senparc.Weixin.MP.CommonAPIs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace RedPack.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

        // GET: /Sign/
        /// <summary>
        /// 授权
        /// </summary>
        /// <returns></returns>
        public RedirectResult OauthPage()
        {
            bool CheckRegist = AccessTokenContainer.CheckRegistered(Base.Weixin_Appid);
            if (!CheckRegist)
            {
                AccessTokenContainer.Register(Base.Weixin_Appid, Base.Weixin_Appsecret);
            }
            string access_token = AccessTokenContainer.GetToken(Base.Weixin_Appid);
            //此页面引导用户点击授权
            string url = OAuthApi.GetAuthorizeUrl(Base.Weixin_Appid, "http://" + Request.Url.Host + "/Sign/index?userkey=" + Request.UserHostAddress, "slgh", OAuthScope.snsapi_base);
            return Redirect(url);
        }
        public ActionResult SendRedPack(string code, string state, string userkey)
        {
            //验证回话是否注册
            var CheckRegist = JsApiTicketContainer.CheckRegistered(Base.Weixin_Appid);
            if (!CheckRegist)
            {
                JsApiTicketContainer.Register(Base.Weixin_Appid, Base.Weixin_Appsecret);
            }
            OAuthAccessTokenResult usertoken = new OAuthAccessTokenResult();
            //获取用户Openid
            OAuthUserInfo userinfo = new OAuthUserInfo();
            usertoken = OAuthApi.GetAccessToken("WxAppID".ToString(), "WxAppSecret".ToString(), code);
            //发送红包
            Base.GetCachred(usertoken.openid, "丝路广惠", "丝路广惠祝大家新年快乐", "新年红包", "");
            return View();
        }
    }
}